﻿using Dapper;
using SIG.DAL.Dapper.Model;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SIG.DAL.Dapper.Repositories
{
    public class WorkRepository
    {
        private DbConnection _connection;

        public Work GetById(int id)
        {
            Work result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Get<Work>(id);
            }
            return result;
        }
        public int? Create(Work model)
        {
            int? result;
            using (_connection = Utilities.GetOpenConnection())
            {
              
                    result = _connection.Insert(model);              
            }
            return result;
        }
        public int? Create(Work model, IEnumerable<WorkCategory> categories)
        {
            int? result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Insert(model);
                if (result > 0)
                {
                    if (categories!=null)
                    {
                        foreach (var item in categories)
                        {
                            string query = "INSERT INTO WorkWorkCategorySet(WorkId,CategoryId)VALUES(@WorkId,@CategoryId)";
                            _connection.Execute(query, new { WorkId = result.Value, CategoryId = item.Id });
                        }
                    }
                                       
                }
                 
              
            }
            return result;
        }

        public int Update(Work model)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Update(model);
            }
            return result;
        }
        public int Update(Work model, IEnumerable<WorkCategory> categories)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {               
                result = _connection.Update(model);
                if (result > 0)
                {
                    _connection.DeleteList<WorkWorkCategory>(new { WorkId = model.Id });
                    if (categories != null)
                    {
                        foreach (var item in categories)
                        {
                            _connection.Execute("insert WorkWorkCategorySet(WorkId, CategoryId) values(@WorkId, @CategoryId)", new { WorkId = model.Id, CategoryId = item.Id });
                            // _connection.Insert(new WorkWorkCategorySet { WorkId = model.Id, CategoryId = item.Id });
                        }
                    }
                   
                }                           

            }
            return result;
        }
        public int Delete(Work model)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Delete(model);
            }
            return result;
        }

        public int Delete(int id)
        {
            int result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.Delete<Work>(id);
            }
            return result;
        }

        public IEnumerable<Work> GetActiveItems()
        {
            IEnumerable<Work> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.GetList<Work>(new { Active = true });
            }
            return result;
        }

        public Work GetPrev(int id)
        {
            Work result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.GetList<Work>( "where Active = 1 and Id < @Id", new { Id = id })
                    .OrderByDescending(m=>m.Id).FirstOrDefault();
            }
            return result;
        }
        public Work GetNext(int id)
        {
            Work result;
            using (_connection = Utilities.GetOpenConnection())
            {
                result = _connection.GetList<Work>("where Active = 1 and Id > @Id", new { Id = id })
                    .OrderByDescending(m => m.Id).FirstOrDefault();
            }
            return result;
        }
        //public IEnumerable<Work> GetListPagedRecommendItems(int pageIndex, int pageSize, out int totalCount)
        //{
        //    IEnumerable<Work> result;
        //    using (_connection = Utilities.GetOpenConnection())
        //    {
        //        var sqlCount = "SELECT   COUNT(*) AS Expr1 FROM WorkWorkCategorySet RIGHT JOIN  WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE(WorkWorkCategorySet.CategoryId = @CategoryId) AND(WorkSet.Active = 1)";
        //        var sql = "SELECT  WorkSet.* FROM WorkWorkCategorySet RIGHT JOIN WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE WorkWorkCategorySet.CategoryId = @CategoryId AND WorkSet.Active = 1 AND WorkSet.Recommend = 1 ORDER BY WorkSet.CreatedDate DESC";

        //        totalCount = _connection.ExecuteScalar<int>(sqlCount, new { categoryId });
        //        result = _connection.Query<Work>(sql, new { categoryId }).ToList();
        //        // result = _connection.GetListPaged<Work>(pageIndex, pageSize, "where Active=1 and CategoryId = @CategoryId", "CreatedDate desc", new { CategoryId = categoryId });
        //    }
        //    return result;

        //}
        public IEnumerable<Work> GetListPagedRecommendItems(int pageIndex, int pageSize, int parentId, string keyword, out int totalCount)
        {
            IEnumerable<Work> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                var sqlCount = "SELECT COUNT(*) AS Expr1 FROM " +
                    "(SELECT DISTINCT  WorkSet.* FROM WorkWorkCategorySet Right JOIN  WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE WorkSet.Active=1  AND WorkSet.Recommend = 1 ";

                var sql = "SELECT  * from (SELECT " +
                    "* , ROW_NUMBER() OVER(ORDER BY CreatedDate DESC) AS RowNum FROM(SELECT DISTINCT  WorkSet.* " +
                    " FROM WorkWorkCategorySet Right JOIN WorkSet ON " +
                     " WorkWorkCategorySet.WorkId = WorkSet.Id WHERE WorkSet.Active=1 AND WorkSet.Recommend = 1 ";

                if (parentId > 0)
                {
                    sqlCount = sqlCount + " and WorkWorkCategorySet.CategoryId = @CategoryId ";
                    sql = sql + " and WorkWorkCategorySet.CategoryId = @CategoryId ";
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    keyword = keyword.Replace("[", "[[]").Replace("%", "[%]");
                    keyword = "%" + keyword + "%";

                    sqlCount = sqlCount + " and (WorkSet.Title like @Keyword  or WorkSet.Body like @Keyword)";
                    sql = sql + " and (WorkSet.Title like @Keyword  or WorkSet.Body like @Keyword) ";
                }
                sqlCount = sqlCount + ") AS RESULT";
                sql = sql + ") AS RESULT ) as tblproducts WHERE RowNum >= @StartIndex AND RowNum< @EndIndex ORDER BY RowNum";

                totalCount = _connection.ExecuteScalar<int>(sqlCount, new { Keyword = keyword, CategoryId = parentId });
                result = _connection.Query<Work>(sql, new { StartIndex = (pageIndex - 1) * pageSize + 1, EndIndex = pageIndex * pageSize + 1, Keyword = keyword, CategoryId = parentId }).ToList();

            }
            return result;

        }


        //public IEnumerable<Work> GetListPagedAcitveItems(int pageIndex, int pageSize, int categoryId, out int totalCount)
        //{
        //    IEnumerable<Work> result;
        //    using (_connection = Utilities.GetOpenConnection())
        //    {
        //        var sqlCount = "SELECT   COUNT(*) AS Expr1 FROM WorkWorkCategorySet RIGHT JOIN  WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE(WorkWorkCategorySet.CategoryId = @CategoryId) AND(WorkSet.Active = 1)";
        //        var sql = "SELECT  WorkSet.* FROM WorkWorkCategorySet RIGHT JOIN WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE(WorkWorkCategorySet.CategoryId = @CategoryId) AND (WorkSet.Active = 1) ORDER BY WorkSet.CreatedDate DESC";

        //        totalCount = _connection.ExecuteScalar<int>(sqlCount, new { categoryId });
        //        result = _connection.Query<Work>(sql, new { categoryId }).ToList();
        //       // result = _connection.GetListPaged<Work>(pageIndex, pageSize, "where Active=1 and CategoryId = @CategoryId", "CreatedDate desc", new { CategoryId = categoryId });
        //    }
        //    return result;

        //}
        //public IEnumerable<Work> GetListPagedAcitveItems(int pageIndex, int pageSize,  out int totalCount)
        //{
        //    IEnumerable<Work> result;
        //    using (_connection = Utilities.GetOpenConnection())
        //    {
        //        var sqlCount = "SELECT COUNT(*) AS Expr1 FROM WorkWorkCategorySet INNER JOIN  WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE(WorkSet.Active = 1)";
        //        var sql = "SELECT  WorkSet.* FROM WorkWorkCategorySet INNER JOIN WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE (WorkSet.Active = 1) ORDER BY dbo.WorkSet.CreatedDate DESC";

        //        totalCount = _connection.ExecuteScalar<int>(sqlCount);
        //        result = _connection.Query<Work>(sql).ToList();
        //        //totalCount = _connection.RecordCount<Work>("where Active=1");
        //        //result = _connection.GetListPaged<Work>(pageIndex, pageSize, "where Active=1", "CreatedDate desc");
        //    }
        //    return result;
        //}


        public IEnumerable<Work> GetListPagedAcitveItems(int pageIndex, int pageSize, int parentId, string keyword, out int totalCount)
        {
            IEnumerable<Work> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                var sqlCount = "SELECT COUNT(*) AS Expr1 FROM " +
                    "(SELECT DISTINCT  WorkSet.* FROM WorkWorkCategorySet Right JOIN  WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE WorkSet.Active=1 ";

                var sql = "SELECT  * from (SELECT " +
                    "* , ROW_NUMBER() OVER(ORDER BY CreatedDate DESC) AS RowNum FROM(SELECT DISTINCT  WorkSet.* " +
                    " FROM WorkWorkCategorySet Right JOIN WorkSet ON " +
                     " WorkWorkCategorySet.WorkId = WorkSet.Id WHERE WorkSet.Active=1 ";

                if (parentId > 0)
                {
                    sqlCount = sqlCount + " and WorkWorkCategorySet.CategoryId = @CategoryId ";
                    sql = sql + " and WorkWorkCategorySet.CategoryId = @CategoryId ";
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    keyword = keyword.Replace("[", "[[]").Replace("%", "[%]");
                    keyword = "%" + keyword + "%";

                    sqlCount = sqlCount + " and (WorkSet.Title like @Keyword  or WorkSet.Body like @Keyword)";
                    sql = sql + " and (WorkSet.Title like @Keyword or WorkSet.Body like @Keyword) ";
                }
                sqlCount = sqlCount + ") AS RESULT";
                sql = sql + ") AS RESULT ) as tblproducts WHERE RowNum >= @StartIndex AND RowNum< @EndIndex ORDER BY RowNum";

                totalCount = _connection.ExecuteScalar<int>(sqlCount, new { Keyword = keyword, CategoryId = parentId });
                result = _connection.Query<Work>(sql, new { StartIndex = (pageIndex - 1) * pageSize + 1, EndIndex = pageIndex * pageSize + 1, Keyword = keyword, CategoryId = parentId }).ToList();

            }
            return result;

        }


        public IEnumerable<Work> GetListPagedItems(int pageIndex, int pageSize, int parentId, string keyword, out int totalCount)
        {
            IEnumerable<Work> result;
            using (_connection = Utilities.GetOpenConnection())
            {
                var sqlCount = "SELECT COUNT(*) AS Expr1 FROM " +
                    "(SELECT DISTINCT  WorkSet.* FROM WorkWorkCategorySet Right JOIN  WorkSet ON WorkWorkCategorySet.WorkId = WorkSet.Id WHERE 1=1 ";

                var sql = "SELECT  * from (SELECT " +
                    "* , ROW_NUMBER() OVER(ORDER BY CreatedDate DESC) AS RowNum FROM(SELECT DISTINCT  WorkSet.* "+
                    " FROM WorkWorkCategorySet Right JOIN WorkSet ON " +
                     " WorkWorkCategorySet.WorkId = WorkSet.Id WHERE 1 = 1 ";

                if (parentId > 0)
                {
                    sqlCount = sqlCount + " and WorkWorkCategorySet.CategoryId = @CategoryId ";
                    sql = sql + " and WorkWorkCategorySet.CategoryId = @CategoryId ";
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    keyword = keyword.Replace("[", "[[]").Replace("%", "[%]");
                    keyword = "%" + keyword + "%";

                    sqlCount = sqlCount + " and (WorkSet.Title like @Keyword  or WorkSet.Body like @Keyword)";
                    sql = sql + " and (WorkSet.Title like @Keyword  or WorkSet.Body like @Keyword) ";
                }
                sqlCount = sqlCount + ") AS RESULT";
                sql = sql + ") AS RESULT ) as tblproducts WHERE RowNum >= @StartIndex AND RowNum< @EndIndex ORDER BY RowNum";

                totalCount = _connection.ExecuteScalar<int>(sqlCount, new { Keyword = keyword, CategoryId = parentId });
                result = _connection.Query<Work>(sql, new { StartIndex= (pageIndex-1)* pageSize + 1, EndIndex = pageIndex * pageSize + 1,  Keyword = keyword, CategoryId = parentId }).ToList();
               
            }
            return result;

        }

    }

}
